<template>
  <div class="common-wrap">
    <QueryForm
      ref="conditionForm"
      module="trunkLine"
      :searchBtnLoading="loading"
      v-model:searchForm="searchForm"
      v-model:search-column="searchColumn"
      @handle-search="onSearch"
    />
    <div class="common-box">
      <el-row style="height: 40px" class="con-button-rows">
        <ButtonGroup
          :disabledDelete="multipleSelection.length === 0"
          :disabledEdit="multipleSelection.length !== 1"
          :hasPermiAdd="['common:trunkLine:add']"
          :hasPermiDelete="['common:trunkLine:delete']"
          :hasPermiEdit="['common:trunkLine:edit']"
          @add="onAdd"
          @edit="onEdit"
          @delete="onDelete"
        ></ButtonGroup>
      </el-row>
      <MyTable
        tableId="trunkLine"
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading"
        :pageVo="pageVo"
        ref="commonTable"
        moduleName="trunkLine"
        @handleSelectionChange="handleSelectionChange"
        @handle-page-change="handlePageChange"
      ></MyTable>
    </div>
    <el-drawer
      v-model="drawer"
      direction="rtl"
      size="80%"
      resizable
      :title="$t(title || '干线')"
    >
      <MyForm
        v-if="drawer"
        ref="commonForm"
        v-model:formData="formData"
        v-model:columns="formColumns"
        :saveBtnLoading="saveBtnLoading"
        :formButtons="false"
        background="#fff"
        @cancel="drawer = false"
      >
      </MyForm>
    </el-drawer>
    <Add
      v-if="dialogVisible"
      v-model:visible="dialogVisible"
      :currRow="currRow"
      :isType="isType"
      @onSubmit="onSearch"
    ></Add>
  </div>
</template>

<script setup lang='tsx'>
import { ref, reactive, onMounted, onUnmounted, onActivated } from "vue";
import { useI18n } from "vue-i18n";
import Add from "./components/add.vue";
import * as api from "@/api/index.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { hasPermi } from "@/utils/mUtils.js";
import {
  queryFormColumnFilters,
  getSubZhEn,
  tabelColumnFilters,
} from "@/utils/mUtils.js";
let { t } = useI18n();

defineOptions({
  name: "TrunkLine",
});
const pageVo = reactive({
  pageSize: 50,
  total: 10,
  currentPage: 1,
  status: true,
});
const loading = ref(true);
const dataSource = ref([]);
const columns = ref([
  {
    type: "checkbox",
    width: 50,
    align: "center",
    fixed: "left",
  },
  {
    title: "序号",
    type: "seq",
    width: 60,
    fixed: "left",
  },
  {
    field: "lineName",
    title: "干线名称",
    slots: {
      default: ({ row }) => {
        return [
          <el-button
            type="primary"
            link
            onClick={() => {
              onEditList(row);
            }}
          >
            {row.lineName || ""}
          </el-button>,
        ];
      },
    },
  },
  {
    field: "typeName",
    title: "业务类型",
  },
  {
    field: "status",
    title: "状态",
    slots: {
      default: ({ row }) => {
        return [
          <el-switch
            disabled={!hasPermi(["common:trunkLine:switch"])}
            v-model={row.status}
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #dcdfe694"
            active-value={"1"}
            inactive-value={"0"}
            onChange={() => {
              onChangeType(row);
            }}
          ></el-switch>,
        ];
      },
    },
  },
  {
    field: "createByName",
    title: "创建人",
  },
  {
    field: "createTime",
    title: "创建时间",
  },
  {
    field: "updateByName",
    title: "更新人",
  },
  {
    field: "updateTime",
    title: "更新时间",
  },
]);
const searchForm = ref({});
const searchColumn = ref([
  {
    type: "label_select",
    label: "业务类型",
    options: [],
    prop: "typeCode",
  },
  {
    type: "label_input",
    label: "干线名称",
    prop: "lineName",
  },
]);
const dialogVisible = ref(false);
const multipleSelection = ref([]);
const currRow = ref({});
const isType = ref("add");
const drawer = ref(false);
const commonForm = ref();
const title = ref("");
const formData = ref({
  detailsList: [],
});
const formColumns = ref([
  {
    title: "",
    structure: [
      {
        type: "tabel",
        prop: "detailsList",
        tableIndex: 0,
        height: 500,
        hasPermiEdit: ["common:trunkLine:detailsEdit"],
        hasPermiAdd: ["common:trunkLine:detailsAdd"],
        hasPermiDelete: ["common:trunkLine:detailsDelete"],
        columns: [
          {
            type: "checkbox",
            width: 50,
            fixed: "left",
            align: "center",
          },
          {
            field: "code",
            title: "航线代码",
            editRender: {},
            slots: { edit: "input_edit" },
          },
          {
            field: "loadingPortCode",
            title: "起运港",
            editRender: {},
            params: {
              options: [],
              change: (val, rowIndex, row, options) => {
                row.loadingPortName = val.option.label;
              },
              key: "portName",
              value: "portCode",
              label: "portName",
              transfer: true,
            },
            slots: { edit: "select_edit" },
            formatter: ({ cellValue, row }) => {
              return row.loadingPortName;
            },
            labelKey: {
              loadingPortCode: "loadingPortCode",
              loadingPortName: "loadingPortName",
            },
          },
          {
            field: "deliveryPortCode",
            title: "目的港",
            editRender: {},
            params: {
              options: [],
              change: (val, rowIndex, row, options) => {
                row.deliveryPortName = val.option.label;
              },
              key: "portName",
              value: "portCode",
              label: "portName",
              transfer: true,
            },
            slots: { edit: "select_edit" },
            formatter: ({ cellValue, row }) => {
              return row.deliveryPortName;
            },
            labelKey: {
              deliveryPortCode: "deliveryPortCode",
              deliveryPortName: "deliveryPortName",
            },
          },
          {
            field: "dischargePortCode",
            title: "卸货港",
            editRender: {},
            params: {
              options: [],
              change: (val, rowIndex, row, options) => {
                row.dischargePortName = val.option.label;
              },
              key: "portName",
              value: "portCode",
              label: "portName",
              transfer: true,
            },
            slots: { edit: "select_edit" },
            formatter: ({ cellValue, row }) => {
              return row.dischargePortName;
            },
            labelKey: {
              dischargePortCode: "dischargePortCode",
              dischargePortName: "dischargePortName",
            },
          },
          {
            field: "providerCode",
            title: "船司",
            editRender: {},
            slots: { edit: "remoteSelect_edit" },
            params: {
              params: {
                searchKey: "providerNameZh",
                name: "providerNameZh",
                keyValue: "providerCode",
                abbreviation: "providerAbbr",
                displayKey: {
                  customizeLeft: "providerCode",
                  customizeRight: "customizeCenter",
                },
                showCustomizedOption: true,
                queryId: true,
              },
              apiModule: api.default.common.serviceProvider.list,
              handleRemoteChange: (selectedRow, rowIndex, row) => {
                row.providerName = selectedRow.providerNameZh;
              },
            },
            formatter: ({ cellValue, row }) => {
              return row.providerName;
            },
          },
          {
            field: "berth",
            title: "挂靠码头",
            editRender: {},
            slots: { edit: "input_edit" },
          },
          {
            field: "transitTime",
            title: "航程天数",
            editRender: {},
            slots: { edit: "input_edit" },
            params: {
              type: "number",
            },
          },
        ],
        editRules: {
          code: [
            {
              required: true,
              message: t("请填写航线代码"),
            },
          ],
          loadingPortCode: [
            {
              required: true,
              message: t("请选择起运港"),
            },
          ],
          deliveryPortCode: [
            {
              required: true,
              message: t("请选择目的港"),
            },
          ],
          dischargePortCode: [
            {
              required: true,
              message: t("请选择卸货港"),
            },
          ],
          providerCode: [
            {
              required: true,
              message: t("请选择船司"),
            },
          ],
          berth: [
            {
              required: true,
              message: t("请选择挂靠码头"),
            },
          ],
          transitTime: [
            {
              required: true,
              message: t("请输入航程天数"),
            },
          ],
        },
        multipleSelection: [],
        buttonType: ["add", "delete"],
        batchDelete: true,
        keepSource: true,
        changeEditNeedTrigger: false,
        keepSourceKey: "code",
        tableId: "trunkLineDetails",
        onDelete: (black) => {
          onDeleteDetails(black);
        },
        handleEditClosed: (row, rowIndex, resolve, reject, black) => {
          save(row, rowIndex, resolve, reject, black);
        },
      },
    ],
  },
]);
const saveBtnLoading = ref(false);
onMounted(() => {
  onSearch();
  onGetSub();
  portList();
});
const onGetSub = () => {
  getSubZhEn({
    code: "005",
  }).then((res) => {
    queryFormColumnFilters(searchColumn.value, "typeCode").options = res["005"];
  });
};
const list = () => {
  loading.value = true;
  api.default.common.trunkLine
    .list({
      ...searchForm.value,
      pageNum: pageVo.currentPage,
      pageSize: pageVo.pageSize,
    })
    .then((res) => {
      dataSource.value = res.rows;
      loading.value = false;
      pageVo.total = res.total;
    })
    .catch(() => {
      loading.value = false;
    });
};

const onAdd = () => {
  isType.value = "add";
  if (multipleSelection.value.length != 0) {
    currRow.value = multipleSelection.value[0];
  }
  dialogVisible.value = true;
};
const onEdit = () => {
  isType.value = "edit";
  currRow.value = multipleSelection.value[0];
  dialogVisible.value = true;
};
const onEditList = (row) => {
  title.value = row.lineName;
  currRow.value = { ...row };
  drawer.value = true;
  detailsList();
};
const onChangeType = (row) => {
  api.default.common.trunkLine.edit({ ...row }).then(() => {
    onSearch();
  });
};
const onDelete = () => {
  const ids = multipleSelection.value.map((item) => item.id);
  ElMessageBox.confirm(t("是否确定删除当前选择数据？"), t("提示"), {
    confirmButtonText: t("确定"),
    cancelButtonText: t("取消"),
    type: "warning",
  })
    .then(() => {
      api.default.common.trunkLine.remove(ids).then(() => {
        ElMessage.success(t("删除成功"));
        onSearch();
      });
    })
    .catch(() => {});
};
const handleSelectionChange = (list) => {
  multipleSelection.value = list;
};
const handlePageChange = (val) => {
  const { currentPage, pageSize } = val;
  pageVo.currentPage = currentPage;
  pageVo.pageSize = pageSize;
  list();
};
const onSearch = () => {
  pageVo.currentPage = 1;
  list();
};
const detailsList = async () => {
  const { data } = await api.default.common.trunkLine.detailsList({
    lineId: currRow.value?.id,
  });
  formData.value.detailsList = data;
};
const onDeleteDetails = (ids) => {
  api.default.common.trunkLine.detailsRemove(ids).then(() => {
    ElMessage.success(t("删除成功"));
    detailsList();
  });
};
const save = async (row, rowIndex, resolve, reject, black) => {
  try {
    if (!row.id) {
      await api.default.common.trunkLine.detailsAdd({
        ...row,
        lineId: currRow.value?.id,
      });
      detailsList();
      ElMessage.success(t("新增成功"));
    } else {
      await api.default.common.trunkLine.detailsEdit(row);
      ElMessage.success(t("修改成功"));
    }
    resolve();
  } catch (e) {
    reject();
  }
};
const portList = async () => {
  const { rows } = await api.default.common.port.list({
    pageSize: 300,
    type: 1,
  });
  tabelColumnFilters(
    formColumns.value[0].structure[0].columns,
    "loadingPortCode"
  ).params.options = rows;
  tabelColumnFilters(
    formColumns.value[0].structure[0].columns,
    "deliveryPortCode"
  ).params.options = rows;
  tabelColumnFilters(
    formColumns.value[0].structure[0].columns,
    "dischargePortCode"
  ).params.options = rows;
};
</script>

<style lang="scss" scoped>
.pcMenu {
  height: 100%;
  width: 100%;
  background: #fff;
}
</style>